package org.jeecg.controller;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.domain.Goods;
import org.jeecg.domain.User;
import org.jeecg.result.ResultTool;
import org.jeecg.service.GoodsService;
import org.jeecg.service.HistoryService;
import org.jeecg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/history")
public class HistoryController {

    @Autowired
    private UserService userService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping(value = "/getHistory",method = RequestMethod.GET)
    public ResultTool getHistory(@RequestParam("username") String username){
        if (username == null){
            return new ResultTool(400,"获取失败");
        }
        User user = userService.queryByUsername(username);
        if (user == null){
            return new ResultTool(400,"获取失败");
        }
        List<Goods> goods = historyService.getHistory(username);
        return new ResultTool(goods,200);
    }

    @RequestMapping(value = "/addHistory",method = RequestMethod.POST)
    public ResultTool addHistory(@RequestBody JSONObject jsonObject){
        String username = (String) jsonObject.get("username");
        String goodId = (String) jsonObject.get("goodId");
        User user = userService.queryByUsername(username);
        Goods goods = goodsService.queryGoods(goodId);
        if (user == null || goods == null){
            return new ResultTool(400,"添加历史记录失败");
        }
        Boolean result = historyService.addHistory(username, goodId);
        if (result){
            return new ResultTool(200,"添加成功");
        }
        return new ResultTool(400,"添加失败");
    }
}
